//
//  TTResourceCenter.m
//  Tint
//
//  Created by Kevin Wu on 9/18/12.
//  Copyright (c) 2012 EACAN Century. All rights reserved.
//

#import "TTResourceCenter.h"


@interface TTResourceCenter (Private)

+ (NSString *)absolutePathFromName:(NSString *)name;

@end

@implementation TTResourceCenter (Private)

+ (NSString *)absolutePathFromName:(NSString *)name
{
    if ( [name length] > 0 ) {
        if ( [name isAbsolutePath] ) {
            return name;
        }
        return [[NSBundle mainBundle] pathForResource:name ofType:nil];
    }
    return nil;
}

@end




@implementation TTResourceCenter


#pragma mark - Accessors

@synthesize resourceMap = _resourceMap;



#pragma mark - Memory

- (id)init
{
    self = [super init];
    if ( self ) {
        _resourceMap = [[NSMutableDictionary alloc] init];
    }
    return self;
}

- (void)dealloc
{
    TTRelease(_resourceMap);
    [super dealloc];
}



#pragma mark - Public

static TTResourceCenter *sharedResourceCenter = nil;

+ (TTResourceCenter *)sharedObject
{
    if ( sharedResourceCenter == nil ) {
        sharedResourceCenter = [[self alloc] init];
    }
    return sharedResourceCenter;
}

+ (BOOL)hasSharedObject
{
    return ( sharedResourceCenter != nil );
}

+ (void)destroySharedObject
{
    if ( sharedResourceCenter ) {
        TTRelease(sharedResourceCenter);
    }
}



- (id)setResource:(id)resource forName:(NSString *)name
{
    [_resourceMap setObject:resource forKeyIfNotNil:name];
    return [_resourceMap objectForKey:name];
}

- (id)resourceForName:(NSString *)name
{
    return [_resourceMap objectForKey:name];
}

- (BOOL)hasResourceForName:(NSString *)name
{
    return ( [_resourceMap objectForKey:name] != nil );
}

- (void)removeResourceForName:(NSString *)name
{
    [_resourceMap removeObjectForKeyIfNotNil:name];
}




- (UIImage *)setImage:(UIImage *)image forName:(NSString *)name
{
    NSString *path = [[self class] absolutePathFromName:name];
    [_resourceMap setObject:image forKeyIfNotNil:path];
    return [_resourceMap objectForKey:path];
}

- (UIImage *)imageForName:(NSString *)name
{
    NSString *path = [[self class] absolutePathFromName:name];
    UIImage *image = [_resourceMap objectForKey:path];
    if ( image == nil ) {
        image = [[UIImage alloc] initWithContentsOfFile:path];
        [_resourceMap setObject:image forKeyIfNotNil:path];
        TTRelease(image);
        
        image = [_resourceMap objectForKey:path];
    }
    return image;
}

- (BOOL)hasImageForName:(NSString *)name
{
    NSString *path = [[self class] absolutePathFromName:name];
    return ( [_resourceMap objectForKey:path] != nil );
}

- (void)removeImageForName:(NSString *)name
{
    NSString *path = [[self class] absolutePathFromName:name];
    [_resourceMap removeObjectForKeyIfNotNil:path];
}



- (void)clearAll
{
    [_resourceMap removeAllObjects];
}

@end
